package com.rachel.pickerview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Scroller;

/**
 * Created by zhengshaorui on 2017/7/31.
 */

public class ScrollTest extends View {
    private static final String TAG = "zsr";
    private Scroller mScroller;
    private GestureDetector mGestureDetector;
    public ScrollTest(Context context) {
        super(context);
    }

    public ScrollTest(Context context, AttributeSet attrs) {
        super(context, attrs);
        mScroller = new Scroller(context);
        mGestureDetector =  new GestureDetector(context,new onFlingGestureListener());
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
               // scrollTo(-10,0); //向右
                Log.d(TAG, "onClick: ");
               // mScroller.startScroll(mScroller.getCurrX(),0,-100,0);
               // invalidate();
            }
        });
    }

    public ScrollTest(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private float mMoveLength;
    private float lastX = 0;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event)){
            return true;
        }

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                mMoveLength += event.getX() - lastX;
                scrollTo(-(int) mMoveLength,0);
                lastX = event.getX();
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(getResources().getColor(R.color.colorAccent));
        canvas.drawCircle(100,100,50,paint);
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (mScroller.computeScrollOffset()){
            scrollTo(mScroller.getCurrX(),0);
            Log.d(TAG, "computeScroll: "+mScroller.getCurrX());
            invalidate();
        }
    }



    class onFlingGestureListener extends GestureDetector.SimpleOnGestureListener{
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            mScroller.fling((int)-mMoveLength,0,(int)velocityX,0,-10,-100,990,990);
            Log.d(TAG, "你大爷的");
            invalidate();
            return false;
        }
    }
}
